/*
功能：隐藏百度贴吧帖子列表签名档图片
创建：2012.03.16
更新：2012年3月19日 12:07:35
    2019年2月13日11:52:39
作者：笃行天下
主页：http://getcrx.cn
*/
const DELAY_KILLEDICON = 3000;
let isOpen = true;

function getTime() {
  var str = '',
    d = new Date(),
    h = d.getHours(),
    m = d.getMinutes(),
    s = d.getSeconds();
  str = h + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
  return str;
}

function setBadge(text, color) {
  clearTimeout(window.t);
  chrome.browserAction.setBadgeText({
    "text": text || ''
  });
  color && chrome.browserAction.setBadgeBackgroundColor({
    "color": color
  });
}

function removeBadge(delay) {
  //移除标记
  clearTimeout(window.t);
  window.t = setTimeout(function () {
    setBadge();
  }, delay || 0);
}

function switchIcon() {
  if (!isOpen) { //sign allowed
    var redColor = [255, 0, 0, 50];
    setBadge('Dis', redColor);
  } else {
    removeBadge();
  }
}

const queryQuestionTabs = (callback) => {
  chrome.tabs.query({
    url: '*://zhidao.baidu.com/question/*',
  }, (tabs) => {
    if (callback) {
      callback(tabs);
    }
  });
};

chrome.extension.onRequest.addListener(
  function (request, sender, sendResponse) {
    switch (request.action) {
      case 'getIsOpen':
        sendResponse({
          isOpen: isOpen
        });
        break;

      case 'setKilledNum':
        if (request.killedNum > 0) {
          setBadge(request.killedNum, [255, 0, 0, 100]);
          removeBadge(DELAY_KILLEDICON);
        }
        break;

      default:
        break;
    }
  }
);

chrome.browserAction.onClicked.addListener(function (tabs) {
  isOpen = !isOpen;

  switchIcon();

  queryQuestionTabs((tabs) => {
    tabs.forEach((tab) => {
      chrome.tabs.sendMessage(tab.id, {
        action: 'change-breadth',
        isOpen,
      });
    });
  });
});

switchIcon();

/** 将贴吧图片转换为可作为签名档的地址 */
const convertSignImg = (tiebapic) => {
  const u = new URL(tiebapic);
  u.host = 'imgsrc.baidu.com';
  u.protocol = 'http:';
  return u.toString();
};

/**
 * 提取签名档图片地址
 * 用法：右键点击贴吧内的图片
 */
chrome.contextMenus.create({
  title: '提取签名档',
  contexts: ['image'],
  targetUrlPatterns: ['*://*.baidu.com/*'],
  onclick(info) {
    const {
      srcUrl,
    } = info;
    alert(convertSignImg(srcUrl));
  }
}, function callback() {

});